<template>
  <div class="overhaul-workList">
    <div class="tableConten">
      <div class="tebleDiv">
        <div class="instructions">作业表单的内容会自动保存</div>
        <!-- <div class="instructions">
          <i class="el-icon-loading" v-if="savaLoading"></i>
          <i class="el-icon-circle-check" v-else>最近保存：{{saveTime}}</i>
        </div>-->
      </div>
    </div>
    <el-tabs v-model="tabActive" type="card" @tab-click="tabClick">
      <!-- 专业 -->
      <template v-for="(item,index) in majorsData">
        <el-tab-pane :label="item.majorName" :key="index">
          <workInstruction
            :ref="'instruction_'+index"
            disabled
            :formData="item"
            :workBookList="item.instructions"
          ></workInstruction>

          <div class="tableConten w100">
            <div class="itemTitle">作业表单：</div>
            <div class="tebleDiv">
              <div class="tebleDiv-top">
                <el-collapse
                  v-model="item.collapseActive"
                  accordion
                  @change="(val)=>handleChange(val,item)"
                >
                  <!-- 专业下表单 -->
                  <template v-for="(formItem,formIndex) in item.forms">
                    <el-collapse-item :key="formIndex" :name="formIndex">
                      <template slot="title">
                        <div class="collapseTitle">
                          <span class="collapseLeft">
                            <span class="lable">表单名{{formIndex+1}}：{{formItem.name}}</span>
                            <span class="lable">{{formItem.code}}</span>
                          </span>
                        </div>
                      </template>
                      <div class="tableConten">
                        <div class="workForm">
                          <editForm
                            :formConfig="workConfig"
                            :ref="'workForm_'+index+'_'+formIndex"
                            :formData="formItem"
                          ></editForm>
                        </div>
                      </div>
                      <div class="processTable">
                        <!-- v-if="formItem.itemDTOs.length" -->
                        <editTableExpand
                          :tableSetting="workProcessDetails"
                          :tableData="formItem.itemDTOs"
                          :stepLevel="formItem.stepLevel"
                          :hideBtn="hideBtn"
                          :ref="'devic_'+index+'_'+formIndex"
                          rowKey="ids"
                        >
                          <template #itemParams="{ editFormInfo }">
                            <el-form
                              :model="itemParams"
                              ref="ruleForm"
                              label-width="120px"
                              class="demo-ruleForm"
                            >
                              <template v-for="(item,index) in editFormInfo.itemParams">
                                <el-form-item
                                  :label="item.name+'('+item.unit+'):'"
                                  prop="name"
                                  :key="index"
                                >
                                  <el-input
                                    v-model="item.value"
                                    @change="val=>inputChange(val,item)"
                                    :disabled="item.disabled"
                                  ></el-input>
                                </el-form-item>
                              </template>
                            </el-form>
                          </template>
                        </editTableExpand>
                      </div>

                      <div class="tableConten fileDiv">
                        <div class="itemTitle">附件:</div>
                        <div class="tebleDiv">
                          <attachFormNew
                            style="width: 60%"
                            :disabled="showBtn"
                            :attachSetting="attachSetting"
                            :businessType="formItem.id"
                            isDelete
                            multiple
                            isInstantUpload
                            :ref="'workFile_'+index+'_'+formIndex"
                          ></attachFormNew>
                        </div>
                      </div>
                    </el-collapse-item>
                  </template>
                </el-collapse>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </template>
    </el-tabs>
    <signature v-if="showSignature" @doSign="verResults" :showSignature.sync="showSignature"></signature>
  </div>
</template>
<script>
import {
  saveTableData, //作业过程项-列值修改（含确认状态和备注）
  saveVariable, //作业过程-数据记录变量
  saveWorkForm, //新增或修改(表单,作业过程)
  updateSignInfo, //签名
  getWorkListApi //根据作业表单ID查详情
} from "@/api/orderManagement/overhaul";
import attachFormNew from "@/components/attach/attachFormNew";
import editTableExpand from "../editTableExpand";
import signature from "@/components/signature";
import workInstruction from "../publicModule/workInstruction"; /* 作业指导书 */
export default {
  props: {
    formData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    //是否可编辑
    disabled: {
      type: Boolean,
      default: false
    },
    orderIde: {
      type: String,
      default: null
    },
    pageType: {
      type: String,
      default: ""
    }
  },
  components: { attachFormNew, signature, editTableExpand, workInstruction },

  data() {
    return {
      activeName: "0",
      tabActive: "0",
      showSignature: false,
      savaLoading: false,
      saveTime: "",
      tabList: [],
      workerList: [],
      majorsData: [],
      workFormData: {},
      workConfig: {
        itemArr: [
          {
            label: "负责人",
            prop: "joberName", //多选时，字段要为数组类型
            propArr: "joberArr",
            idsStr: "jober",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: obj => {
              this.saveOperateForm();
            },
            required: true,
            span: 8
          },
          {
            label: "安全监督员",
            prop: "safeManName", //多选时，字段要为数组类型
            propArr: "safeManArr",
            idsStr: "safeMan",
            multiple: false, //是否多选
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: obj => {
              this.saveOperateForm();
            },
            required: true,
            span: 8
          },
          {
            label: "工作班成员",
            prop: "workerName", //多选时，字段要为数组类型
            propArr: "workerArr",
            idsStr: "worker",
            multiple: true, //是否多选
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: obj => {
              let workerName = null;
              let arr = [];
              this.workerList = [];
              obj.map((i, index) => {
                let user = {
                  jobDept: i.orgId,
                  jobDeptName: i.orgName,
                  worker: i.id || i.value,
                  workerName: i.name || i.label,
                  type: i.isOutOrg,
                  orderId: this.workListData.id,
                  sort: index + 1
                };
                this.workerList.push(user);
              });
              this.saveOperateForm();
            },
            required: true,
            rows: 2,
            span: 8
          },
          {
            label: "作业时间",
            prop: "workTime",
            type: "datetimerange",
            required: true,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() < Date.now() - 3600 * 1000 * 24;
              }
            },
            methods: obj => {
              this.saveOperateForm();
            },
            span: 8
          },
          {
            label: "存在问题:",
            prop: "problem",
            type: "textarea",
            maxlength: "500",
            span: 24,
            rows: 4,
            methods: (val, obj) => {
              this.saveOperateForm(obj);
            }
          },
          {
            label: "改进建议:",
            prop: "suggestion",
            type: "textarea",
            maxlength: "500",
            span: 24,
            rows: 4,
            methods: (val, obj) => {
              this.saveOperateForm(obj);
            }
          }
        ]
      },
      currentMajor: {}, //当前专业
      currentRow: null, //当前行
      typeId: null,

      hideBtn: false,
      workListData: {},
      itemParams: {},
      rules: [],
      workProcessData: [],
      /* 作业表单-作业准备 */
      workListDetails: {
        title: "",
        select: false,
        addMethons: false,
        maxHeight: 400,
        btnArr: [], //"edit",
        data: [],
        column: [
          {
            label: "类别",
            prop: "type",
            type: "disableText",
            width: 180
          },
          {
            label: "名称",
            prop: "tools",
            type: "disableText"
          },
          {
            label: "确认状态",
            prop: "result",
            type: "checkbox",
            method: (obj, item) => {
              this.confirmStatus(obj, item);
            }
          }
        ]
      },
      /* 作业表单-作业过程 */
      workProcessDetails: {
        title: "作业过程:",
        select: false,
        addMethons: false,
        maxHeight: 400,
        column: [
          {
            label: "序号",
            prop: "sort",
            type: "disableText"
          },
          {
            label: "作业内容",
            prop: "context",
            width: "150px",
            type: "disableText"
          },
          {
            label: "作业标准",
            prop: "contextStandard",
            width: "220px",
            type: "disableText"
          },
          {
            label: "作业风险&控制措施",
            prop: "risk",
            width: "220px",
            type: "disableText"
          },
          {
            label: "数据记录项",
            prop: "itemParams",
            type: "formItem",
            width: "300px"
          },
          {
            label: "验收级别",
            prop: "levelabel",
            type: "disableText"
          },
          {
            label: "确认状态",
            prop: "result",
            type: "checkbox",
            methods: (obj, item) => {
              this.confirmProcessStatus(obj, item, "result");
            }
          },
          {
            label: "备注",
            prop: "desc",
            type: "textarea",
            width: "220px",
            methods: (obj, item) => {
              this.confirmProcessStatus(obj, item, "desc");
            }
          },
          {
            label: "已签名人",
            prop: "signerName",
            type: "disableText"
          }
        ],
        buttonArr: [
          {
            name: "验收签名",
            isShow: row => {
              return true;
            },
            methods: (row, index) => {
              //判断内容是否填写完整
              let canSign = true;
              let mes = "";
              let { itemParams, result } = row;
              if (result != true) {
                mes = "状态未确认!";
                canSign = false;
              } else {
                for (let i = 0; i < itemParams.length; i++) {
                  if (itemParams[0].value == null) {
                    mes = "数据记录项未填写完整！";
                    canSign = false;
                    break;
                  }
                }
              }
              if (canSign) {
                this.currentRow = row;
                //测试
                this.showSignature = true;
              } else {
                this.$message.warning(mes);
              }
            }
          }
        ]
      },
      workData: [],
      option: {
        1: "Ⅰ",
        2: "Ⅱ",
        3: "Ⅲ"
      },
      //附件设置
      attachSetting: {
        businessId: "", //单据的ID
        businessType: ""
      },
      isComplete: false,
      currentCollapse: null,
      locationInfo: null
    };
  },
  computed: {
    showBtn() {
      return !(
        this.workListData.status == "IN_EXECUTE" && this.pageType == "edit"
      );
    },
    showBookList() {
      let bookLength = this.workFormData.orderInstructionBeanList || [];
      return bookLength != 0;
    }
  },
  watch: {
    formData: {
      handler(val, old) {
        this.workListData = JSON.parse(JSON.stringify(val));
        this.currentMajor = this.workListData.majors[0];
        this.attachSetting.businessId = val.id;
        this.initData();
      },
      deep: true
    },
    "formData.status": {
      handler(val) {
        //更新数据
        this.initData();
      },
      deep: true
    }
  },
  created() {},
  mounted() {
    this.initData();
  },
  methods: {
    //初始化数据
    async initData() {
      this.workListData = JSON.parse(JSON.stringify(this.formData));
      if (this.workListData.majors) {
        this.currentMajor = this.workListData.majors[0];
        this.currentCollapse = 0;
      }
      this.attachSetting.businessId = this.formData.id;
      this.majorsData = this.workListData.majors;
      let status = this.workListData.status;
      let config = [];
      //深度拷贝数组对象(可拷贝函数)
      $.extend(true, config, this.workConfig.itemArr);
      config.map(i => {
        if (
          this.workListData.status == "IN_EXECUTE" &&
          this.pageType == "edit"
        ) {
          i.disabled = false;
        } else {
          i.disabled = true;
        }
      });
      this.workConfig.itemArr = config;
      if (this.workListData.status == "IN_EXECUTE" && this.pageType == "edit") {
        this.hideBtn = false;
      } else {
        this.hideBtn = true;
      }
      let majorsArr = JSON.parse(JSON.stringify(this.workListData.majors));
      setTimeout(() => {
        majorsArr.map((i, index) => {
          i.forms.map((j, formIndex) => {
            let {
              joberName,
              jober,
              safeManName,
              safeMan,
              startTime,
              endTime,
              formWorkers,
              itemDTOs
            } = j;
            if (startTime != null) {
              j.workTime = [startTime, endTime];
            }
            if (jober) {
              let joberOption = this.$utils.getOptionData(
                joberName,
                jober,
                "0"
              ); //0本单位
              this.$refs[
                "workForm_" + index + "_" + formIndex
              ][0].setItemOption("joberName", joberOption); //负责人
              j.joberArr = jober; //负责人
            }
            if (safeMan) {
              let safeManOption = this.$utils.getOptionData(
                safeManName,
                safeMan,
                "0"
              );
              this.$refs[
                "workForm_" + index + "_" + formIndex
              ][0].setItemOption("safeManName", safeManOption); //安全监督员
              j.safeManArr = safeMan; //安全监督员
            }
            /* 工作班成员 */
            if (formWorkers.length > 0) {
              let name = [];
              let idArr = [];
              let typeArr = [];
              formWorkers.map(k => {
                name.push(k.workerName);
                idArr.push(k.worker);
                typeArr.push(k.type);
              });
              let workerOption = this.$utils.getOptionData(
                name.toString(),
                idArr.toString(),
                typeArr.toString()
              );
              this.$refs[
                "workForm_" + index + "_" + formIndex
              ][0].setItemOption("workerName", workerOption); //工作班成员
              j.workerName = name.toString();
              j.workerArr = idArr;
              j.worker = idArr.toString();
            }
          });
        });
        this.majorsData = majorsArr;
      }, 100);
    },
    async getFormData(index, formIndex) {
      let data = await this.$refs[
        "workForm_" + index + "_" + formIndex
      ][0].getFormData();
      return data;
    },

    getTableData(index, formIndex) {
      return this.$refs["devic_" + index + "_" + formIndex][0].getTableData();
    },
    // changeTableData(data) {
    //   data.map(i => {
    //     i.editable = true;
    //   });
    // },
    //确认作业状态
    confirmStatus(obj, item) {
      let { id, result } = obj;
      let form = {
        id,
        result
      };
      saveReadyApi(form).then(res => {
        this.$message.success("保存成功！");
        this.updataTime();
      });
    },
    /* 数据记录项修改 */
    inputChange(val, item) {
      saveVariable(item).then(res => {
        this.$message.success("保存成功！");
        this.updataTime();
      });
    },
    //确认过程状态
    confirmProcessStatus(obj, item, type) {
      let form = {
        itemId: obj.id, //作业过程项id
        key: type, //作业过程项列名, 确认状态: key=result, 备注: key=desc,
        value: obj[type] //作业过程项列值
      };
      saveTableData(form).then(res => {
        this.$message.success("保存成功！");
        this.updataTime();
      });
    },
    //修改作业表单FORM
    async saveOperateForm() {
      this.savaLoading = true;
      let { collapseActive: formIndex, index } = this.currentMajor;
      let data = await this.$refs[
        "workForm_" + index + "_" + formIndex
      ][0].getFormData(false);
      let {
        id,
        majorId,
        name,
        overhaulId,
        standardId,
        jober,
        joberName,
        safeMan,
        safeManName,
        workTime,
        problem,
        suggestion,
        stepLevel
      } = data;
      let form = {
        id,
        majorId,
        name,
        overhaulId,
        standardId,
        stepLevel,
        jober,
        joberName,
        safeMan,
        safeManName,
        formWorkers: this.workerList || [],
        endTime: null,
        startTime: null,
        problem,
        suggestion
      };
      if (workTime) {
        form.endTime = workTime[1];
        form.startTime = workTime[0];
      }
      saveWorkForm(form).then(res => {
        if (res.code == 200) {
          this.$message.success("保存成功！");
          let nowForm = res.data;
          this.workListData.majors[this.tabActive].forms[this.currentCollapse] =
            res.data;
          this.updataTime();
        }
        setTimeout(() => {
          this.savaLoading = false;
        }, 300);
      });
    },
    updataTime() {
      this.saveTime = this.$utils.getCurrentDate();
    },
    /* 获取作业指导书 */
    getBookFile(item, type) {
      let form = {
        businessId: item.instructionId
      };
      getAttachList(form).then(res => {
        let data = res.data[0];
        if (res.data.length) {
          if (type == "preview") {
            this.preBook(data);
          } else if (type == "download") {
            this.downloadBook(data);
          }
        }
      });
    },

    //预览指导书
    preBook(item) {
      window.open(
        process.env.VUE_APP_BASEURL +
          "/eam-common-web/attachment/preview/?fileId=" +
          item.id
      );
      return true;
    },
    //下载指导书
    downloadBook(item) {
      this.$utils.downloadFile(item.id, item.name, item.path);
    },
    //签名
    verResults(obj) {
      let { account, name } = obj;
      let form = {
        orderType: "overhaul",
        signer: account,
        signerName: name,
        orderId: this.workListData.id,
        itemId: this.currentRow.id
      };
      updateSignInfo(form).then(res => {
        // 重新获取详情的数据，单个form数据更新，
        this.getSignformData();
      });
    },
    //获取表单的详情
    async getSignformData() {
      let res = await getWorkListApi(this.currentRow.formId);
      let data = res.data;
      let { itemDTOs, stepLevel } = data;
      this.initTableData(itemDTOs, stepLevel);
      let formIndex = null;
      let forms = this.currentMajor.forms || [];
      for (let i = 0; i < forms.length; i++) {
        if (forms[i].id == this.currentRow.formId) {
          formIndex = i;
          break;
        }
      }

      let filterItemDTOs = this.getFilterItemDTOs(itemDTOs)
      this.$refs["devic_" + this.tabActive + "_" + formIndex][0].setTableData(
        filterItemDTOs
      );
    },
    // 过滤出满足条件的数据并重新排序(按后端的sort)
    getFilterItemDTOs(rootDTOs, sort = '') {
      let filterItemDTOs = rootDTOs.filter((item) => {
        return this.currentRow.majorId == item.majorId && this.currentRow.formId == item.formId
      })
      filterItemDTOs.forEach((item, index) => {
        item.sort = sort == '' ? (index + 1) : sort + '.' + (index + 1)
        if(item.children && item.children.length > 0) {
          this.getFilterItemDTOs(item.children, item.sort)
        }
      })
      return filterItemDTOs
    },
    //处理作业项目的表格数据
    initTableData(data, stepLevel) {
      let status = this.workListData.status;
      data.map((item, i) => {
        item.sort = i + 1;
        item.ids = item.id;
        if (["IN_EXECUTE"].includes(status) && this.pageType == "edit") {
          item.editable = true;
        } else {
          item.editable = false;
        }
        item.rowIndex = i;
        item.levelabel = this.option[item.level];
        item.itemParamString = this.customsHandleConfirm(item.itemParams);
        let signs = item.signs || [];
        let signName = [];
        if (signs.length) {
          signs.map(k => {
            signName.push(k.signerName);
          });
          item.signerName = signName.toString();
        }
        let childrenArr = item.children || [];
        item.children = item.children || [];
        delete item.createTime;
        if (childrenArr.length != 0) {
          childrenArr.forEach((child, index) => {
            if (status == "IN_EXECUTE" && this.pageType == "edit") {
              child.editable = true;
            } else {
              child.editable = false;
            }
            let downSigns = child.signs || [];
            if (downSigns.length > 0) {
              let name = [];
              downSigns.map(i => {
                name.push(i.signerName);
              });
              child.signerName = name.toString();
            }
            child.parentIndex = i;
            child.rowIndex = index;
            child.sort = `${i + 1}.${index + 1}`;
            child.ids = child.id;
            child.levelabel = this.option[child.level];
            child.itemParamString = this.customsHandleConfirm(child.itemParams);
            delete child.createTime;
          });
        }
      });
    },
    //通过逗号把几个输入框的值拼接起来
    customsHandleConfirm(list) {
      let string = "";
      list.forEach((item, i) => {
        delete item.createTime;
        if (i == 0) {
          string += `${item.name}(${item.unit})`;
        } else {
          string += `,${item.name}(${item.unit})`;
        }
      });
      //通过逗号把几个输入框的值拼接起来
      return string;
    },
    handleChange(val, item) {
      this.currentCollapse = val;
      item.collapseActive = val;
      this.currentMajor = item;
    },
    //tab页的切换
    tabClick(tab, event) {
      let data = this.workListData.majors[this.tabActive];
      this.currentMajor = JSON.parse(JSON.stringify(data));
      this.currentMajor.collapseActive = this.currentCollapse;
    }
  }
};
</script>
<style lang="less">
.overhaul-workList {
  .tableConten {
    display: flex;
    flex-flow: wrap nowrap;
    margin-top: 10px;
    .redPoint {
      color: red;
    }
    .itemTitle {
      width: 120px;
      text-align: justify;
      text-justify: distribute-all-lines;
      text-align-last: justify;
      padding: 0px 10px;
    }
    .tebleDiv {
      width: calc(100% - 120px);
      text-align: justify;
      .tebleDiv {
        width: calc(100% - 120px);
      }
    }
    .tebleDiv-bottom {
      margin-top: 10px;
    }
  }
  .fileDiv {
    margin-bottom: 10px;
  }
  .saveTime {
    color: #bebebe;
    font-size: 12px;
  }
  .processTable {
    .el-input__inner {
      height: 30px;
      line-height: 30px;
    }
  }
  .bookContent {
    width: 400px;
    border: 1px solid #ebebeb;
    border-radius: 4px;
    padding: 10px;
  }
  .instructions {
    width: 300px;
    height: 25px;
    line-height: 25px;
    margin-bottom: 10px;
  }
  .line {
    height: 30px;
    width: 100%;
    border: 1px dashed #ebebeb;
    padding: 0px 10px;
    display: flex;
    flex-flow: wrap nowrap;
    justify-content: space-between;
  }
  .line + .line {
    margin-top: 10px;
  }
  .workForm {
    width: 100%;
    .el-form-item__label {
      width: 100px !important;
    }
    .el-form-item__content {
      margin-left: 100px !important;
    }
  }
  .el-checkbox__inner::after {
    height: 10px;
    left: 7px;
    width: 4px;
  }
}
</style>